//----------------------------------------
// Page
//----------------------------------------
let getSelectionByName = function(name) {
    let eles = document.querySelectorAll('input[name=' + name + ']');
    let result = []
    if (eles) {
        for(let i = 0; i < eles.length; ++i) {
            let ele = eles[i];
            if (ele.checked) {
                let id = ele.getAttribute('data-id')
                if (id) {
                    result.push(parseInt(id));
                }
            }
        }
    }

    return result;
};
let getArgValue = function(argName) {
    if (!argName) {
        return '';
    }

    let argEle = document.querySelector('#' + argName);
    if (!argEle) {
        return '';
    }

    let v = argEle.value;
    if (argEle.type === 'date') {
        return v.replace(/-/g, '');
    } else if (argEle.type = 'datetime-local') {
        return v.replace(/[:-]/g, '');
    } else if (argEle.type === 'button' || argEle.type === 'submit') {
        return '';
    } else {
        return v;
    }
};
let combineArgs = function(argNames) {
    let ret = '';

    // 通过连字符连接各个参数值。
    // 参数值中包含的连字符被转义。
    for (let i = 0; i < argNames.length; ++i) {
        let argName = argNames[i];
        let v = getArgValue(argName)
        v = v.trim().replace(/-/g, '"-"').substring(0, 32);
        ret = ret + v + '-';
    }

    // 删除尾部多余的连字符。
    ret = ret.replace(/-+$/, '');

    return ret;
};
let setQueryString = function(r, kv) {
    if (kv === null || kv === undefined) {
        kv = {};
    }
    let s = location.search;
    let qi = s.indexOf('?');
    s = s.substring(qi + 1);
    let params = s.split('&');
    let newSearch = '';
    for (let i = 0; i < params.length; ++i) {
        let param = params[i].split('=')
        let k = param[0];
        let v = param[1];
        if (k === '_t') continue;
        if (k in kv) {
            v = kv[k];
            delete kv[k]
        }
        if (v) {
            console.log(k, '=', v);
            newSearch = newSearch + '&' + k + '=' + v;
        }
    }
    for (let k in kv) {
        let v = kv[k];
        if (v) {
            console.log(k, '=', v);
            newSearch = newSearch + '&' + k + '=' + v;
        }
    }
    newSearch = newSearch + '&_t=' + Math.floor(new Date().getTime() / 1000);

    let newUrl = location.protocol + '//' + location.host + location.pathname + '?' + newSearch.substring(1);

    if (r) {
        location.replace(newUrl);
    } else {
        location.href = newUrl;
    }
};
let reloadPage = function(r) {
    if (r === undefined) r = false;
    setQueryString(r);
};
let jumpTo = function(i,j) {
    setQueryString(false, {'page': i + ',' + j});
};
let showOverlay = function() {
    let overlay = document.querySelector('#overlay');
    overlay.style.width = (window.innerWidth + 2) + 'px';
    overlay.style.height = (window.innerHeight + 2) + 'px';
    overlay.style.visibility = 'visible';
};
let hideOverlay = function() {
    let overlay = document.querySelector('#overlay');
    overlay.style.width = '0px';
    overlay.style.height = '0px';
    overlay.style.visibility = 'hidden';
};
let makeCenter = function(o, el) {
    let left = (o.clientWidth - el.offsetWidth) / 2;
    let top = (o.clientHeight - el.offsetHeight) / 2;

    if (left < 0) left = 0;
    if (top < 0) top = 0;

    el.style.top = top + 'px';
    el.style.left = left + 'px';
};
let removeClass = function(el, c) {
    c = c.trim();
    if (!c) return;
    el.className = el.className.split(/\s+/).filter(item => item && item !== c).join(' ');
};
let addClass = function(el, c) {
    c = c.trim();
    if (!c) return
    let cna = el.className.split(/\s+/).filter(item => item);
    if (!(c in cna)) {
        cna.push(c);
    }
    el.className = cna.join(' ');
};
//----------------------------------------
// Ajax
//----------------------------------------
let rpc = function(settings) {
    return new Promise((resolve, reject) => {
        if (settings.data) {
            let up = new URLSearchParams();
            for(let key in settings.data) {
                up.append(key, settings.data[key]);
            }
            settings.data = up;
        }

        // Promise
        axios.request({
            url: settings.url,
            method: settings.method,
            params: settings.params,
            data: settings.data
        })
        .then(rsp => {
            let contentType = '';
            if (rsp.headers && rsp.headers['content-type']) {
                contentType = rsp.headers['content-type'];
            }
            if (!contentType.startsWith('application/json')) {
                let nonJsonRsp = document.querySelector('#nonJsonRsp');
                if (nonJsonRsp) {
                    let frame = nonJsonRsp.querySelector('iframe');
                    nonJsonRsp.querySelector('.close').addEventListener('click', () => {
                        frame.contentDocument.open();
                        frame.contentDocument.write('');
                        frame.contentDocument.close();
                        nonJsonRsp.style.visibility = 'hidden';
                        hideOverlay();
                    });
                    frame.contentDocument.open();
                    frame.contentDocument.write(rsp.data);
                    frame.contentDocument.close();
                    // overlay
                    showOverlay();
                    // center
                    nonJsonRsp.style.top = window.innerHeight * .05 + 'px';
                    nonJsonRsp.style.left = (window.innerWidth - nonJsonRsp.clientWidth) / 2 + 'px';
                    frame.style.height = window.innerHeight * .667 + 'px';
                    nonJsonRsp.style.visibility = 'visible';
                }
                reject('illegal content type, expected "application/json", but "' + contentType);
            } else {
                resolve(rsp.data);
            }
        });
    });
};

let rpcGet = function(settings) {
    if (typeof settings === 'string') {
        settings = {
            url: settings,
            method: 'get'
        };
    } else {
        settings['method'] = 'get';
    }
    return rpc(settings);
};

let rpcPost = function(settings) {
    settings['method'] = 'post';
    return rpc(settings);
};

let rpcPut = function(settings) {
    settings['method'] = 'put';
    return rpc(settings);
};

let rpcDelete = function(settings) {
    settings['method'] = 'delete';
    return rpc(settings);
};
